import { useState, useEffect } from 'react'
import {
  Modal,
  Form,
  Input,
  Select,
  Radio,
  InputNumber,
} from '@arco-design/web-react'
import type { Step } from '@/types'

const FormItem = Form.Item
const Option = Select.Option
const TextArea = Input.TextArea

interface StepFormModalProps {
  visible: boolean
  step: Step | null
  onSubmit: (step: Step) => void
  onCancel: () => void
}

export default function StepFormModal({
  visible,
  step,
  onSubmit,
  onCancel,
}: StepFormModalProps) {
  const [form] = Form.useForm()
  const [stepType, setStepType] = useState<number>(1)

  useEffect(() => {
    if (visible && step) {
      form.setFieldsValue({
        name: step.name,
        stepType: step.stepType,
        ...parseStepConfig(step.stepConfig),
      })
      setStepType(step.stepType)
    } else if (visible) {
      form.resetFields()
      setStepType(1)
    }
  }, [visible, step, form])

  const handleSubmit = () => {
    form.validate().then((values) => {
      const { name, stepType, ...configData } = values

      const newStep: Step = {
        id: step?.id || 0,
        stageId: step?.stageId || 0,
        name,
        stepType,
        order: step?.order || 0,
        stepConfig: JSON.stringify(configData),
      }

      onSubmit(newStep)
      form.resetFields()
    })
  }

  const parseStepConfig = (configStr: string) => {
    try {
      return JSON.parse(configStr || '{}')
    } catch {
      return {}
    }
  }

  // 根据不同的 stepType 渲染不同的配置表单
  const renderConfigFields = () => {
    switch (stepType) {
      case 1: // Git Clone
        return (
          <>
            <FormItem
              label="仓库地址"
              field="repository"
              rules={[{ required: true, message: '请输入仓库地址' }]}
            >
              <Input placeholder="https://github.com/user/repo.git" />
            </FormItem>
            <FormItem
              label="分支"
              field="branch"
              rules={[{ required: true, message: '请输入分支名' }]}
            >
              <Input placeholder="main" />
            </FormItem>
            <FormItem label="凭据 ID" field="credentialId">
              <Input placeholder="可选，私有仓库需要" />
            </FormItem>
          </>
        )

      case 2: // Build
        return (
          <>
            <FormItem
              label="构建工具"
              field="buildTool"
              rules={[{ required: true, message: '请选择构建工具' }]}
            >
              <Select placeholder="选择构建工具">
                <Option value="dotnet">.NET</Option>
                <Option value="maven">Maven</Option>
                <Option value="gradle">Gradle</Option>
                <Option value="npm">NPM</Option>
                <Option value="yarn">Yarn</Option>
                <Option value="cargo">Cargo (Rust)</Option>
              </Select>
            </FormItem>
            <FormItem
              label="构建命令"
              field="command"
              rules={[{ required: true, message: '请输入构建命令' }]}
            >
              <TextArea
                placeholder="例如: dotnet build -c Release"
                autoSize={{ minRows: 2, maxRows: 4 }}
              />
            </FormItem>
            <FormItem label="工作目录" field="workingDirectory">
              <Input placeholder="默认为项目根目录" />
            </FormItem>
          </>
        )

      case 3: // Test
        return (
          <>
            <FormItem
              label="测试框架"
              field="testFramework"
              rules={[{ required: true, message: '请选择测试框架' }]}
            >
              <Select placeholder="选择测试框架">
                <Option value="xunit">xUnit</Option>
                <Option value="nunit">NUnit</Option>
                <Option value="jest">Jest</Option>
                <Option value="pytest">Pytest</Option>
              </Select>
            </FormItem>
            <FormItem
              label="测试命令"
              field="command"
              rules={[{ required: true, message: '请输入测试命令' }]}
            >
              <TextArea
                placeholder="例如: dotnet test"
                autoSize={{ minRows: 2, maxRows: 4 }}
              />
            </FormItem>
            <FormItem label="覆盖率报告" field="coverageReport">
              <Radio.Group>
                <Radio value={true}>启用</Radio>
                <Radio value={false}>禁用</Radio>
              </Radio.Group>
            </FormItem>
          </>
        )

      case 5: // Docker Build
        return (
          <>
            <FormItem
              label="Dockerfile 路径"
              field="dockerfilePath"
              rules={[{ required: true, message: '请输入 Dockerfile 路径' }]}
            >
              <Input placeholder="./Dockerfile" />
            </FormItem>
            <FormItem
              label="镜像名称"
              field="imageName"
              rules={[{ required: true, message: '请输入镜像名称' }]}
            >
              <Input placeholder="myapp:latest" />
            </FormItem>
            <FormItem label="构建参数" field="buildArgs">
              <TextArea
                placeholder="例如: --build-arg VERSION=1.0"
                autoSize={{ minRows: 2, maxRows: 4 }}
              />
            </FormItem>
          </>
        )

      case 6: // Docker Push
        return (
          <>
            <FormItem
              label="镜像名称"
              field="imageName"
              rules={[{ required: true, message: '请输入镜像名称' }]}
            >
              <Input placeholder="myapp:latest" />
            </FormItem>
            <FormItem
              label="Registry 地址"
              field="registryUrl"
              rules={[{ required: true, message: '请输入 Registry 地址' }]}
            >
              <Input placeholder="docker.io" />
            </FormItem>
            <FormItem label="凭据 ID" field="credentialId">
              <Input placeholder="Registry 登录凭据" />
            </FormItem>
          </>
        )

      case 10: // Custom Script
        return (
          <>
            <FormItem
              label="脚本类型"
              field="scriptType"
              rules={[{ required: true, message: '请选择脚本类型' }]}
            >
              <Select placeholder="选择脚本类型">
                <Option value="bash">Bash</Option>
                <Option value="powershell">PowerShell</Option>
                <Option value="python">Python</Option>
                <Option value="node">Node.js</Option>
              </Select>
            </FormItem>
            <FormItem
              label="脚本内容"
              field="script"
              rules={[{ required: true, message: '请输入脚本内容' }]}
            >
              <TextArea
                placeholder="输入脚本内容"
                autoSize={{ minRows: 5, maxRows: 10 }}
              />
            </FormItem>
            <FormItem label="超时时间(秒)" field="timeout">
              <InputNumber placeholder="默认 300 秒" min={1} />
            </FormItem>
          </>
        )

      default:
        return (
          <FormItem label="配置" field="config">
            <TextArea
              placeholder="JSON 格式配置"
              autoSize={{ minRows: 3, maxRows: 6 }}
            />
          </FormItem>
        )
    }
  }

  return (
    <Modal
      title={step ? '编辑 Step' : '添加 Step'}
      visible={visible}
      onOk={handleSubmit}
      onCancel={onCancel}
      style={{ width: 600 }}
    >
      <Form form={form} layout="vertical" autoComplete="off">
        <FormItem
          label="Step 名称"
          field="name"
          rules={[{ required: true, message: '请输入 Step 名称' }]}
        >
          <Input placeholder="请输入 Step 名称" />
        </FormItem>

        <FormItem
          label="Step 类型"
          field="stepType"
          rules={[{ required: true, message: '请选择 Step 类型' }]}
        >
          <Select
            placeholder="选择 Step 类型"
            onChange={(value) => setStepType(value as number)}
          >
            <Option value={1}>Git Clone</Option>
            <Option value={2}>Build</Option>
            <Option value={3}>Test</Option>
            <Option value={4}>Deploy</Option>
            <Option value={5}>Docker Build</Option>
            <Option value={6}>Docker Push</Option>
            <Option value={7}>K8s Deploy</Option>
            <Option value={8}>NuGet Push</Option>
            <Option value={9}>Maven Deploy</Option>
            <Option value={10}>Custom Script</Option>
          </Select>
        </FormItem>

        {renderConfigFields()}
      </Form>
    </Modal>
  )
}
